package edu.iit.cs553;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.SendMessageRequest;

public class Dispatcher {

	private AmazonSQSClient sqsClient;

	public Dispatcher()
	{
		this.sqsClient = new AmazonSQSClient(new ClasspathPropertiesFileCredentialsProvider());
		sqsClient.setEndpoint("sqs.us-west-2.amazonaws.com");
	}

	public void sendTasksToSQSQueue(List<Map<Integer, Long>> workload)
	{
		int i = 1;
		for (Map<Integer, Long> task : workload)
		{
			System.out.println("Sending task #" + i + " to the SQS queue.");
			sendTaskToSQSQueue(task);
			i++;
		}
	}

	private void sendTaskToSQSQueue(Map<Integer, Long> task)
	{
		String serializedTask = serializeTask(task);
		List<String> queuesUrls = sqsClient.listQueues().getQueueUrls();
		String queueUrl = queuesUrls.get(0);
		sqsClient.sendMessage(new SendMessageRequest(queueUrl, serializedTask));
	}

	private String serializeTask(Map<Integer, Long> task)
	{
		Set<Integer> keySet = task.keySet();
		Iterator<Integer> iterator = keySet.iterator();
		Integer taskId = iterator.next();
		long sleepDuration = task.get(taskId);
		String serializedTask = taskId + " " + sleepDuration;
		return serializedTask;
	}
}
